//
//  ADHomeViewController.swift
//  myBlog
//
//  Created by mac2014 on 16/3/20.
//  Copyright © 2016年 AD. All rights reserved.
//

import UIKit
import SVPullToRefresh

let reusableIdentifier = "cell"

class ADHomeViewController: ADBaseTableViewController {
    
    //MARK: - 属性
    var statuses: [ADStatus]? {
        didSet {
            //当statuses的值改变时触发
            self.tableView.reloadData()
        }
    }
    
    
    //MARK: - 系统方法
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //如果没有登录，直接返回
        if !ADUserAcountViewModel.sharedInstance.isLogin {
            return
        }
        
        setupNavigationBar()
        setupTitleBtn()
        setupTableView()
        
        //加载微博状态数据
        
        ADStatusViewModel.sharedInstance.loadStatuses { (statuses, error) -> () in
            if error != nil {
                //error
                return
            }
            //如果没有错误，将传进来的statuses赋给statuses
            self.statuses = statuses
        }
        
    }

    // MARK: - 自定义方法
    
    //设置tableview：注册cell
    private func setupTableView() {
        tableView.registerClass(ADStatusCell.self, forCellReuseIdentifier: reusableIdentifier)
        
        //自适应高度
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
        //取消设置tableview的分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        //刷新加载数据
        tableView.addPullDownRefreshHandler { () -> () in
            self.reloadNewData()
        }
        //开始刷新
        tableView.startRefreshing()
        
        //上拉加载更多
        
    }
    
    //加载数据
    private func reloadNewData() {
        let since_id = self.statuses?.first?.id ?? 0
        
        ADStatusViewModel.sharedInstance.loadStatuses { (statuses, error) -> () in
            self.tableView.endRefreshing()
            
            if error != nil {
                //加载微博出错
                return
            }
            
            let count = statuses?.count ?? 0
            if count == 0 {
                return
            }
            
            //下拉刷新
            if since_id > 0 {
                self.statuses = statuses! + self.statuses!
            } else {
                self.statuses = statuses
            }
        }
    }
    
    //设置导航栏
    func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButton("navigationbar_friendsearch", target: self, action: "didClickLeftBarButton")
        navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButton("navigationbar_pop", target: self, action: "didClickRightBarButton")
    }
    
    //导航栏按钮的点击事件
    func didClickLeftBarButton() {
        //print("didClickLeftBarButton")
    }

    func didClickRightBarButton() {
        //print("didClickRightBarButton")
    }
    
    //设置导航栏tilte
    func setupTitleBtn() {
        //设置titleBtn的文本框：用户名
        let userName = ADUserAcountViewModel.sharedInstance.userAccount?.screen_name
        let titleBtn = ADHomeViewTitleButton(title: userName ?? "没有名称", imageName: "navigationbar_arrow_down")
        titleBtn.addTarget(self, action: "didClickTitleBtn:", forControlEvents: UIControlEvents.TouchUpInside)

        navigationItem.titleView = titleBtn
    }
    //titleBtn的点击事件:点击选中状态改变；图片翻转；弹出view
    func didClickTitleBtn(button: ADHomeViewTitleButton) {
        //选中状态改变
        button.selected = !button.selected
        //图片翻转动画:如果被选中，则旋转，取消选中则恢复默认状态
        UIView.animateWithDuration(0.3) { () -> Void in
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.0001)) : CGAffineTransformIdentity
        }
        //如果button被点击，
        if button.selected {
            //创建对象
            let popView = ADPopViewController()
            
            //设置popView  modal出来的样式
            popView.modalPresentationStyle = .Popover
            
            //设置代理
            popView.popoverPresentationController?.delegate = self
            
            //设置sourceView
            popView.popoverPresentationController?.sourceView = navigationItem.titleView
            //设置指向中点
            popView.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
            //设置popView显示的大小
            popView.preferredContentSize = CGSize(width: 160, height: 44 * popView.titles.count)
            
            //弹出popView
            presentViewController(popView, animated: true, completion: nil)
        }
    }
    
    // MARK: - Table view data source & delegate
    //返回多少行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //有微博数据返回微博状态数，没有则返回0个
        return statuses?.count ?? 0
    }
    
    //设置cell数据
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(reusableIdentifier, forIndexPath: indexPath) as! ADStatusCell
        //cell的内容设置
        cell.status = statuses?[indexPath.row]

        return cell
    }
}




// MARK: - UIPopoverPresentationControllerDelegate
extension ADHomeViewController: UIPopoverPresentationControllerDelegate {
    //适配当前控制器
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    //收回弹出的控制器
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        
        let titleBtn = navigationItem.titleView as! ADHomeViewTitleButton
        
        didClickTitleBtn(titleBtn)
        
        return true
    }
}





